package com.apps.ftapp.act;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.activity.BaseActivity;
import com.apps.ftapp.activity.LessonDetailActivity;
import com.apps.ftapp.adapter.ListDropDownAdapter;
import com.apps.ftapp.adapter.ShareListAdapter;
import com.apps.ftapp.adapter.ShareListAdapter.MyClickListener;
import com.apps.ftapp.model.FenXiangLieBiaoModel;
import com.apps.ftapp.model.LessonBean;
import com.apps.ftapp.model.Queding;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yyydjk.library.DropDownMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

/**
 * 分享内容列表
 */
public class ShareListActivity extends BaseActivity implements MyClickListener {

    @BindView(R.id.dropDownMenu)
    DropDownMenu dropDownMenu;
    @BindView(R.id.tops)
    LinearLayout tops;

    ListView listView;
    SmartRefreshLayout refreshLayout;

    private ShareListAdapter shareListAdapter;

    private List<FenXiangLieBiaoModel.CoursesharesBean> dataList = new ArrayList<>();

    private String headers[] = {"宗合排序", "全部分类"};
    private List<View> popupViews = new ArrayList<>();
    private ListDropDownAdapter flAdapter;
    private List<LessonBean> fenleiList = new ArrayList<>();
    private ListDropDownAdapter orAdapter;
    private List<LessonBean> orderList = new ArrayList<>();

    private String fenleiId;
    private String orderId;

    //用于记录当前是第几页
    private int curPage = 1;
    //用于记录一页应该请求多少条数据
    private int pageSize = 10;
    //用于记录总页数，在上拉的时候判断还有没有更多数据
    private boolean isEnd = false;

    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_list);
        ButterKnife.bind(this);

        setTitle("选择分享内容");

        loadData(orderId, fenleiId);
    }

    /**
     * http://api.iweishi.cn/course/share?page={$page}
     */
    private void loadData(String orderby, String categoryId) {
        RequestParams params = new RequestParams();
        params.put("orderby", Tools.isNull(orderby));
        params.put("categoryId", Tools.isNull(categoryId));
        params.put("page", curPage + "");
        Async.post("course/share", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody) + "......");
                    FenXiangLieBiaoModel result = gson.fromJson(new String(responseBody), FenXiangLieBiaoModel.class);
                    if (Tools.isIntNull(result.getSuccess()) == 1) {

                        orderList.addAll(LessonBean.traOrder(result.getOrderbyarr()));
                        fenleiList.addAll(LessonBean.traFenlei(result.getCategoryIdarr()));
                        dataList.addAll(result.getCourseshares());

                        L.i("main", fenleiList.size() + "======" + result.getCategoryIdarr().size());
                        initView();
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }


    private void loadData22222(String orderby, String categoryId) {
        RequestParams params = new RequestParams();
        params.put("orderby", Tools.isNull(orderby));
        params.put("categoryId", Tools.isNull(categoryId));
        params.put("page", curPage + "");
        L.i("main", orderby + "......" + categoryId);
        Async.post("course/share", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody) + "......");
                    FenXiangLieBiaoModel result = gson.fromJson(new String(responseBody), FenXiangLieBiaoModel.class);
                    if (Tools.isIntNull(result.getSuccess()) == 1) {

//                        dataList.addAll(result.getCourseshares());

                        shareListAdapter.addRes(result.getCourseshares());

//                        L.i("main",fenleiList.size()+"===2222222222==="+result.getCategoryIdarr().size());
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }


    private void initView() {

        popupViews.clear();
        final ListView lxView = new ListView(getApplicationContext());
        lxView.setDividerHeight(0);
        flAdapter = new ListDropDownAdapter(getApplicationContext(), fenleiList);
        lxView.setAdapter(flAdapter);


        //类别
        lxView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                flAdapter.setCheckItem(position);
                dropDownMenu.setTabText(position == 0 ? headers[0] : fenleiList.get(position).getName());
                dataList.clear();
                fenleiId = fenleiList.get(position).getId();
                loadData22222(orderId, fenleiId);

                dropDownMenu.closeMenu();
            }
        });

        final ListView orderView = new ListView(getApplicationContext());
        orderView.setDividerHeight(0);
        orAdapter = new ListDropDownAdapter(getApplicationContext(), orderList);
        orderView.setAdapter(orAdapter);

        //排抒
        orderView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                orAdapter.setCheckItem(position);
                dropDownMenu.setTabText(position == 0 ? headers[0] : orderList.get(position).getName());
                dataList.clear();
                orderId = orderList.get(position).getId();
                loadData22222(orderId, fenleiId);

                dropDownMenu.closeMenu();
            }
        });


        popupViews.add(orderView);
        popupViews.add(lxView);


        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.fragment_lesson_listview, null);

        listView = view.findViewById(R.id.listView);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, view);

        shareListAdapter = new ShareListAdapter(getApplicationContext(), dataList, this);
        listView.setAdapter(shareListAdapter);

//
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                HashMap<String, Object> map = new HashMap();
//                map.put("id", dataList.get(i).getId());
//                map.put("title", dataList.get(i).getTitle());
//                ActivitySkipUtil.skipAnotherActivity(ShareListActivity.this, LessonDetailActivity.class, map);
//            }
//        });


        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);
                //一般加载数据都是在子线程中，这里我用到了handler
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        curPage = 1;
//                        myOrderAdapter.clearLists()clearLists;
                        loadData22222(orderId, fenleiId);
                    }
                }, 1000);
            }
        });


        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(2000);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        isLoadMore = false;
                        curPage = curPage + 1;
                        L.i("main", "curPage...." + curPage);
                        if (!isEnd) {
                            loadData22222(orderId, fenleiId);
                        } else {
                            Toasty.normal(getApplicationContext(), "没有更多啦O(∩_∩)O").show();

                        }
                    }
                }, 1000);
            }
        });

    }


    public void jumps(final int i) {
        HashMap<String, Object> map = new HashMap();
        map.put("id", dataList.get(i).getId());
        map.put("title", dataList.get(i).getTitle());
        map.put("inviteId", dataList.get(i).getInviteId());
        map.put("mytitle", dataList.get(i).getMytitle());
        ActivitySkipUtil.skipAnotherActivity(ShareListActivity.this, LessonDetailActivity.class, map);
    }

    @Override
    public void clickListener(View v) {
        final int i = (int) v.getTag();
        switch (v.getId()) {
            case R.id.lesson_img:
                jumps(i);
                break;


            case R.id.lesson_type:
                jumps(i);

                break;


            case R.id.lesson_price:

                jumps(i);
                break;


            case R.id.lesson_title:
                jumps(i);

                break;


            case R.id.lesson_fan:
                jumps(i);

                break;

            case R.id.fenxinag:


                final String id = dataList.get(i).getId();

                boolean wrapInScrollView = true;
                final MaterialDialog dialog = new MaterialDialog.Builder(this)
                        .customView(R.layout.fenxiangtanchuang, wrapInScrollView)
                        .contentGravity(GravityEnum.CENTER)
                        .build();


                View view = dialog.getCustomView();

                final EditText editText = view.findViewById(R.id.shhuruderen);

                TextView quxiaoBtn = view.findViewById(R.id.quxiao);
                quxiaoBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                TextView quedingBen = view.findViewById(R.id.queding);
                quedingBen.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String content = editText.getText().toString();
                        if ("".equals(content)) {

                            Toasty.normal(getApplicationContext(), "请输入内容").show();
                            return;
                        }


                        zhixing(i, id, content, dialog);

                    }
                });

//                Window window = dialog.getWindow();
//                window.setBackgroundDrawableResource(android.R.color.transparent);
//                WindowManager.LayoutParams attributes = window.getAttributes();
//                window.getDecorView().setPadding(0,0,0,0); //消除边距
//                DisplayMetrics dm = new DisplayMetrics();
//                window.getWindowManager().getDefaultDisplay().getMetrics(dm);
//                int viewWidth  = dm.widthPixels ;
//                attributes.width = (int)(viewWidth); //设置宽度
//                attributes.height = (int)(viewWidth);
                dialog.show();

                break;
        }
    }


    public void zhixing(final int i, String id, String content, final Dialog dialog) {

        RequestParams params = new RequestParams();
        params.put("userId", Constant.uid);
        params.put("token", Constant.token);
        params.put("id", id + "");
        params.put("mytitle", content + "");
        Async.post("course/share/name", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody) + "......");
                    Queding result = gson.fromJson(new String(responseBody), Queding.class);
                    if (Tools.isIntNull(result.getSuccess()) == 1) {

                        dataList.get(i).setMytitle(result.getMytitle());
                        dataList.get(i).setInviteId(result.getInviteId());

                        dialog.dismiss();

                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("id", result.getInviteId());
                        map.put("title", result.getMytitle());
                        map.put("qrcode", "");
                        ActivitySkipUtil.skipAnotherActivity(ShareListActivity.this, ShareJlDActivity.class, map);


                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }

}
